<?php

namespace app\service;

use app\model\CashMoney;
use app\utils\CashMoneyEmun;
use think\facade\Db;
use app\model\Member;
use app\exception\ParameterException;
use app\model\UserMoney;
use app\utils\UserMoneyEmun;
class CashMoneyService
{
    private $cashMember;
    private $member;

    private $userMoney;
    public function __construct(){
        $this->cashMember = new CashMoney;
        $this->member = new Member;
        $this->userMoney = new userMoney;
    }

    public function list($params){
        $page = $params['page'] ?? 1;
        $pageSize = $params['pageSize'] ?? 10;
        $where = [];
        if(!empty($params['username'])) $where[] = ['member.username', 'like', '%'.trim($params['username']).'%'];
        if(isset($params['status']) && $params['status']!='') $where[] = ['cash_money.status', '=', $params['status']];

        $result = $this->cashMember->join('member', 'cash_money.member_id = member.id', 'LEFT')
            ->join('admin_user', 'cash_money.admin_id = admin_user.id', 'LEFT')
            ->field('cash_money.*, member.nickname, member.username,member.phone,admin_user.username as admin_username')
            ->order(['cash_money.id'=>'DESC'])
            ->where($where)->paginate([
                'list_rows'=> $pageSize,
                'page' => $page
            ])->append(['status_text']);
        $totalPrice = $this->cashMember->where($where)->sum('price');

        if(!empty($result)) {
            $result = $result->toArray();
            $result['total_price'] = $totalPrice;
        }


        return $result;
    }

    public function update($id, $data)
    {
        $admin_id  = request()->_uid;

        $cashMoney = $this->cashMember->find($id);

        if($cashMoney->status != CashMoneyEmun::CASH_MONEY_STATUS_APPLY) throw new ParameterException("只有申请中的才能操作");

        //事务
        Db::startTrans();
        try {

            //提现通过
            if($data['status'] == CashMoneyEmun::CASH_MONEY_STATUS_PASS){
                $data['admin_id'] = $admin_id;
                $member = $this->member->lock(true)->where('id', $cashMoney->member_id)->find();
                if ($member->money < $cashMoney->price) throw new ParameterException("用户余额不足");

                //更新用户余额
                $member->money = sprintf("%.2f", $member->money-$cashMoney->price);//bcsub($member->money, $cashMoney->money, 2);
                $member->save();

                //创建钱包记录
                $this->userMoney->create([
                    'member_id' => $cashMoney->member_id,
                    'price' => (-1)*$cashMoney->real_price,
                    'type' => UserMoneyEmun::USER_MONEY_TYPE_CASH,
                    'remark' => '提现成功',
                    'admin_id' => $admin_id,
                    'balance' => $member->money,
                    'target_id'=> $cashMoney->id
                ]);
            }

            Db::commit();
            return $cashMoney->allowField(['status', 'admin_id'])->save($data);
        } catch (\Exception $e) {
            Db::rollback();
            throw new ParameterException($e->getMessage());
        }
    }

    public function save($param)
    {
        $param['member_id'] = request()->_mid;

        $param['order_sn'] = generateSnowflakeId();
        $minPrice = (new ConfigService())->getByKey('mix_money');
        if(empty($param['price'])) throw new ParameterException("提现金额不能为空");
        if($param['price'] <= 0) throw new ParameterException("提现金额必须大于0");
        //提现2元起
        if($param['price'] < $minPrice) throw new ParameterException("提现金额不能小于{$minPrice}元");
        $member = $this->member->where('id', $param['member_id'])->with(['vip'])->find();

        if(empty($member->alipay_account)) throw new ParameterException("请先绑定支付宝账号");
        if(empty($member->realname)) throw new ParameterException("请先绑定支付宝收款姓名");

        if($param['price'] > $member->money) throw new ParameterException("提现金额不能大于余额");
        $param['status'] = CashMoneyEmun::CASH_MONEY_STATUS_APPLY;

        //vip优先取vip
        $ratio = !empty($member->vip)?$member->vip->discount: (new ConfigService())->getByKey('cash_ratio');

        $param['real_price'] = sprintf("%.2f", $param['price'] * $ratio/100);

        $param['ratio'] = $ratio;

        $param['alipay_account'] = $member->alipay_account;

        $param['realname'] = $member->realname;


        //$param['real_price']=  sprintf("%.2f", $param['price'] - $param['commission_price']);
        $param['commission_price']=  sprintf("%.2f", $param['price'] - $param['real_price']);
        //查看用户是否存在
        if($this->cashMember->where([
            ['member_id','=',$param['member_id']],
            ['status','=',0]
        ])->count() > 0) throw new ParameterException("提现申请处理中，请勿重复申请");

        return $this->cashMember->allowField(['price','member_id','status','real_price','ratio','commission_price'])->create($param);

    }

    public function apiList($params){
        $page = $params['page'] ?? 1;
        $pageSize = $params['pageSize'] ?? 10;
        $where = [];
        $where[]=['member_id','=', request()->_mid];
        $result = $this->cashMember->join('member', 'cash_money.member_id = member.id', 'LEFT')
            ->field('cash_money.*, member.nickname, member.username,member.phone')
            ->order(['cash_money.id'=>'DESC'])
            ->where($where)->paginate([
                'list_rows'=> $pageSize,
                'page' => $page
            ])->append(['status_text']);
        $totalPrice = $this->cashMember->where($where)->sum('price');

        if(!empty($result)) {
            $result = $result->toArray();
            $result['total_price'] = $totalPrice;
        }


        return $result;
    }


}
